import axios from "axios";
import store from "@/store";
import storage from "store";
import notification from "ant-design-vue/es/notification";
import { VueAxios } from "./axios";
import { useMock, production, serverTimeDiff } from "../../config/dev.config";
import appConfig from "@/config/defaultSettings";

const isMockMode = !production && useMock;

// 创建 axios 实例
const request: any = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 10 * 60 * 1000, // 请求超时时间
});

// 异常拦截处理器
const errorHandler = (error: any) => {
  if (error.response) {
    const data = error.response.data;
    let token = "";
    if (!isMockMode) {
      // 从 localstorage 获取 token
      const getters = store?.getters;
      const { ACCESS_TOKEN } = getters?.mainappUtils?.headerKeys;
      token = storage.get(ACCESS_TOKEN);
    }
    if (error.response.status === 404) {
      notification.error({
        message: "404: Not Found",
        description: data?.msg,
      });
    }
    if (error.response.status === 403) {
      notification.error({
        message: "Forbidden",
        description: data.message,
      });
    }
    if (
      error.response.status === 401 &&
      !(data.result && data.result.isLogin)
    ) {
      notification.error({
        message: "Unauthorized",
        description: "Authorization verification failed",
      });
      if (token) {
        store.dispatch("Logout").then(() => {
          setTimeout(() => {
            window.location.reload();
          }, 1500);
        });
      }
    }
  }
  return Promise.reject(error);
};

// request interceptor
// request.interceptors.request.use((config: any) => {
//   config.headers["AppName"] = appConfig.appName;
//   const getters = store?.getters;
//   const {
//     ACCESS_TOKEN,
//     Signature,
//     Serial,
//     QiankunID,
//     HEADER_TENANT,
//     SERVER_TIME_DIFF,
//     UserID,
//     BUSI_NETWORK,
//   } = getters?.mainappUtils?.headerKeys ?? {};

//   if (!isMockMode) {
//     const token = storage.get(ACCESS_TOKEN);
//     if (token) {
//       config.headers[ACCESS_TOKEN] = token;
//     }

//     // 添加菜单租户id
//     const currentTenant = storage.get("currentTenant") || getters?.mainRoute?.meta?.tenantId;
//     config.headers[HEADER_TENANT] = currentTenant;

//     // 添加唯一流水号
//     const { generateNanoid, generateSignature } = getters?.mainappUtils;
//     // config.headers[Serial] = generateNanoid();
//     config.headers[QiankunID] = getters?.mainRoute?.meta?.microPageId;
//     config.headers["CenterRoute"] = store?.getters?.userInfo?.centerRoute;

//     config.headers["XUserRoles"] = store.getters?.userInfo.userRoles;
  
//     // 如果 服务器时间差 存在
//     // const timeDiff = production
//     //   ? storage.get(SERVER_TIME_DIFF) ?? 999
//     //   : serverTimeDiff;

//     const timeDiff =  storage.get(SERVER_TIME_DIFF)

//     const userId = storage.get(UserID);

//     if (userId) {
//       if(config.headers['isBigfileUpload']) {
//         config.headers[Signature] = generateSignature(
//           'isBigfileUpload',
//           // config.data,
//           timeDiff,
//           userId,
//           "2.0"
//         );
//       } else {
//         config.headers[Signature] = generateSignature(
//           config.data,
//           timeDiff,
//           userId,
//           "2.0"
//         );
//       }
//     }
  

//     // 添加生产/办公网域判断
//     config.headers[BUSI_NETWORK] = storage.get(BUSI_NETWORK);
//   }

//   if ((window as any).__POWERED_BY_DUBHE__) {
//     config.baseURL = appConfig.backendPrefix + config.baseURL;
//   }
//   return getters.mainappUtils.microAppRequestInterceptor(appConfig.appName, config);
//   // return config;
// }, errorHandler);

// response interceptor
request.interceptors.response.use((response: any) => {
  const getters = store?.getters;
  // return getters.mainappUtils.microAppResponseInterceptor(appConfig.appName, response.data);
  return response.data;
}, errorHandler);

const installer: any = {
  vm: {},
  install(Vue: any) {
    Vue.use(VueAxios, request);
  },
};

export default request;

export { installer as VueAxios, request as axios };
